////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                            //
//                                                         WNProject                                                          //
//                                                                                                                            //
//            This file is distributed under the BSD 2-Clause open source license. See License.txt for details.               //
//                                                                                                                            //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#ifndef __WN_CONCURRENCY_BENAPHORE_H__
#define __WN_CONCURRENCY_BENAPHORE_H__

#include "WNCore/inc/WNPlatform.h"
#include "WNCore/inc/WNTypes.h"
#include "WNCore/inc/WNMacros.h"

#ifdef _WN_WINDOWS
    #include <windows.h>
#elif defined _WN_LINUX
    #include <pthread.h>
#endif

namespace WNConcurrency {
    class WNBenaphore {
    public:
        WN_INLINE WNBenaphore();
        WN_INLINE ~WNBenaphore();

        WN_INLINE WN_VOID Lock();
        WN_INLINE WN_BOOL TryLock();
        WN_INLINE WN_VOID Unlock();

    private:
        #ifdef _WN_WINDOWS
            HANDLE mHandle;
        #elif defined _WN_LINUX
            pthread_mutex_t mMutex;
        #endif

        WN_ATOM_T mCounter;
    };

    class WNBenaphoreScopeLock {
    public:
        WN_INLINE WNBenaphoreScopeLock(WNBenaphore& _benaphore);
        WN_INLINE ~WNBenaphoreScopeLock();

    private:
        WNBenaphore& mBenaphore;

        WN_BOOL mLocked;
    };
}

#define WN_BENAPHORE_SCOPE_LOCK(_benaphore) WNBenaphoreScopeLock WN_UNIQUE_VARIABLE(benaphore)(_benaphore)

#include "WNConcurrency/inc/WNBenaphore.inl"

#endif // __WN_CONCURRENCY_BENAPHORE_H__